import UIKit
import Photos
import Social

class ShareManager: NSObject {
    
    // MARK: - Main Share Method
    func shareImage(_ image: UIImage, from viewController: UIViewController) {
        let activityViewController = UIActivityViewController(
            activityItems: [image, ShareText.defaultText],
            applicationActivities: [
                SaveToPhotosActivity(),
                ShareToInstagramActivity(),
                ShareToWeChatActivity()
            ]
        )
        
        // Configure for iPad
        if let popover = activityViewController.popoverPresentationController {
            popover.sourceView = viewController.view
            popover.sourceRect = CGRect(x: viewController.view.bounds.midX, y: viewController.view.bounds.midY, width: 0, height: 0)
            popover.permittedArrowDirections = []
        }
        
        // Exclude some default activities that aren't relevant
        activityViewController.excludedActivityTypes = [
            .assignToContact,
            .addToReadingList,
            .openInIBooks
        ]
        
        // Present the share sheet
        viewController.present(activityViewController, animated: true)
    }
    
    // MARK: - Direct Save to Photos
    func saveImageToPhotos(_ image: UIImage, completion: @escaping (Bool, Error?) -> Void) {
        PHPhotoLibrary.requestAuthorization { status in
            guard status == .authorized else {
                DispatchQueue.main.async {
                    completion(false, ShareError.photoLibraryAccessDenied)
                }
                return
            }
            
            PHPhotoLibrary.shared().performChanges({
                PHAssetCreationRequest.creationRequestForAsset(from: image)
            }) { success, error in
                DispatchQueue.main.async {
                    completion(success, error)
                }
            }
        }
    }
    
    // MARK: - Share to Specific Platforms
    func shareToInstagram(_ image: UIImage, from viewController: UIViewController) {
        // Check if Instagram is installed
        guard let instagramURL = URL(string: "instagram://app") else {
            showAlert(title: "Instagram未安装", message: "请先安装Instagram应用", on: viewController)
            return
        }
        
        if UIApplication.shared.canOpenURL(instagramURL) {
            // Try to share to Instagram Stories
            shareToInstagramStories(image, from: viewController)
        } else {
            showAlert(title: "Instagram未安装", message: "请先安装Instagram应用", on: viewController)
        }
    }
    
    private func shareToInstagramStories(_ image: UIImage, from viewController: UIViewController) {
        guard let imageData = image.pngData() else { return }
        
        let pasteboardItems: [String: Any] = [
            "com.instagram.sharedSticker.backgroundImage": imageData,
            "com.instagram.sharedSticker.appID": "StyleFilters"
        ]
        
        UIPasteboard.general.items = [pasteboardItems]
        
        if let url = URL(string: "instagram-stories://share") {
            UIApplication.shared.open(url)
        }
    }
    
    func shareToWeChat(_ image: UIImage, from viewController: UIViewController) {
        // Check if WeChat is installed
        guard let wechatURL = URL(string: "weixin://") else {
            showAlert(title: "微信未安装", message: "请先安装微信应用", on: viewController)
            return
        }
        
        if UIApplication.shared.canOpenURL(wechatURL) {
            // Use system share sheet which will include WeChat if available
            let activityViewController = UIActivityViewController(
                activityItems: [image],
                applicationActivities: nil
            )
            
            if let popover = activityViewController.popoverPresentationController {
                popover.sourceView = viewController.view
                popover.sourceRect = CGRect(x: viewController.view.bounds.midX, y: viewController.view.bounds.midY, width: 0, height: 0)
            }
            
            viewController.present(activityViewController, animated: true)
        } else {
            showAlert(title: "微信未安装", message: "请先安装微信应用", on: viewController)
        }
    }
    
    // MARK: - Helper Methods
    private func showAlert(title: String, message: String, on viewController: UIViewController) {
        DispatchQueue.main.async {
            let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "确定", style: .default))
            viewController.present(alert, animated: true)
        }
    }
}

// MARK: - Share Text Configuration
struct ShareText {
    static let defaultText = "用StyleFilters创作的美图 ✨ #StyleFilters #时尚滤镜 #穿搭"
    
    static func customText(for filterName: String) -> String {
        return "用StyleFilters的\(filterName)滤镜创作 ✨ #StyleFilters #\(filterName) #时尚滤镜"
    }
}

// MARK: - Share Errors
enum ShareError: LocalizedError {
    case photoLibraryAccessDenied
    case imageProcessingFailed
    case platformNotAvailable
    
    var errorDescription: String? {
        switch self {
        case .photoLibraryAccessDenied:
            return "需要相册访问权限来保存照片"
        case .imageProcessingFailed:
            return "图片处理失败"
        case .platformNotAvailable:
            return "分享平台不可用"
        }
    }
}

// MARK: - Custom Activity: Save to Photos
class SaveToPhotosActivity: UIActivity {
    
    private var image: UIImage?
    
    override var activityType: UIActivity.ActivityType? {
        return UIActivity.ActivityType("com.stylefilters.saveToPhotos")
    }
    
    override var activityTitle: String? {
        return "保存到相册"
    }
    
    override var activityImage: UIImage? {
        return UIImage(systemName: "square.and.arrow.down")
    }
    
    override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
        return activityItems.contains { $0 is UIImage }
    }
    
    override func prepare(withActivityItems activityItems: [Any]) {
        image = activityItems.first { $0 is UIImage } as? UIImage
    }
    
    override func perform() {
        guard let image = image else {
            activityDidFinish(false)
            return
        }
        
        PHPhotoLibrary.requestAuthorization { status in
            guard status == .authorized else {
                DispatchQueue.main.async {
                    self.activityDidFinish(false)
                }
                return
            }
            
            PHPhotoLibrary.shared().performChanges({
                PHAssetCreationRequest.creationRequestForAsset(from: image)
            }) { success, _ in
                DispatchQueue.main.async {
                    self.activityDidFinish(success)
                }
            }
        }
    }
}

// MARK: - Custom Activity: Share to Instagram
class ShareToInstagramActivity: UIActivity {
    
    private var image: UIImage?
    
    override var activityType: UIActivity.ActivityType? {
        return UIActivity.ActivityType("com.stylefilters.shareToInstagram")
    }
    
    override var activityTitle: String? {
        return "Instagram"
    }
    
    override var activityImage: UIImage? {
        // You would typically use Instagram's icon here
        return UIImage(systemName: "camera")
    }
    
    override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
        guard activityItems.contains(where: { $0 is UIImage }) else { return false }
        guard let instagramURL = URL(string: "instagram://app") else { return false }
        return UIApplication.shared.canOpenURL(instagramURL)
    }
    
    override func prepare(withActivityItems activityItems: [Any]) {
        image = activityItems.first { $0 is UIImage } as? UIImage
    }
    
    override func perform() {
        guard let image = image,
              let imageData = image.pngData() else {
            activityDidFinish(false)
            return
        }
        
        let pasteboardItems: [String: Any] = [
            "com.instagram.sharedSticker.backgroundImage": imageData,
            "com.instagram.sharedSticker.appID": "StyleFilters"
        ]
        
        UIPasteboard.general.items = [pasteboardItems]
        
        if let url = URL(string: "instagram-stories://share") {
            UIApplication.shared.open(url) { success in
                DispatchQueue.main.async {
                    self.activityDidFinish(success)
                }
            }
        } else {
            activityDidFinish(false)
        }
    }
}

// MARK: - Custom Activity: Share to WeChat
class ShareToWeChatActivity: UIActivity {
    
    private var image: UIImage?
    
    override var activityType: UIActivity.ActivityType? {
        return UIActivity.ActivityType("com.stylefilters.shareToWeChat")
    }
    
    override var activityTitle: String? {
        return "微信"
    }
    
    override var activityImage: UIImage? {
        // You would typically use WeChat's icon here
        return UIImage(systemName: "message")
    }
    
    override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
        guard activityItems.contains(where: { $0 is UIImage }) else { return false }
        guard let wechatURL = URL(string: "weixin://") else { return false }
        return UIApplication.shared.canOpenURL(wechatURL)
    }
    
    override func prepare(withActivityItems activityItems: [Any]) {
        image = activityItems.first { $0 is UIImage } as? UIImage
    }
    
    override func perform() {
        // For WeChat, we'll fall back to the system share sheet
        // which will include WeChat if it's installed
        activityDidFinish(true)
    }
}

// MARK: - Share Analytics (Optional)
class ShareAnalytics {
    
    static func trackShare(platform: String, filterType: String) {
        // Here you would integrate with your analytics service
        // For example: Firebase Analytics, Mixpanel, etc.
        print("📊 Share tracked: Platform=\(platform), Filter=\(filterType)")
    }
    
    static func trackSave(filterType: String) {
        print("📊 Save tracked: Filter=\(filterType)")
    }
}

// MARK: - Social Platform Detection
extension ShareManager {
    
    func getAvailablePlatforms() -> [SocialPlatform] {
        var platforms: [SocialPlatform] = []
        
        // Always available
        platforms.append(.photos)
        platforms.append(.systemShare)
        
        // Check Instagram
        if let instagramURL = URL(string: "instagram://app"),
           UIApplication.shared.canOpenURL(instagramURL) {
            platforms.append(.instagram)
        }
        
        // Check WeChat
        if let wechatURL = URL(string: "weixin://"),
           UIApplication.shared.canOpenURL(wechatURL) {
            platforms.append(.weChat)
        }
        
        // Check Weibo
        if let weiboURL = URL(string: "weibo://"),
           UIApplication.shared.canOpenURL(weiboURL) {
            platforms.append(.weibo)
        }
        
        return platforms
    }
}

enum SocialPlatform {
    case photos
    case instagram
    case weChat
    case weibo
    case systemShare
    
    var displayName: String {
        switch self {
        case .photos: return "保存到相册"
        case .instagram: return "Instagram"
        case .weChat: return "微信"
        case .weibo: return "微博"
        case .systemShare: return "更多分享选项"
        }
    }
    
    var iconName: String {
        switch self {
        case .photos: return "square.and.arrow.down"
        case .instagram: return "camera"
        case .weChat: return "message"
        case .weibo: return "globe"
        case .systemShare: return "square.and.arrow.up"
        }
    }
}